package com.wcc.book.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.wcc.book.entity.Books;
import com.wcc.book.util.JdbcTool;

public class BookService {
	public List<Books> query(int bookId) throws SQLException, ClassNotFoundException{
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		List<Books> book =new ArrayList<Books>();
		
		try {
			con=JdbcTool.craeConnection();
			ps=con.prepareStatement("select id,book_name,book_number,book_sum from book where book_id=?");
			ps.setInt(1, bookId);
			rs=ps.executeQuery();
			while (rs.next()){
				Books books=new Books();
				books.setId(rs.getInt("id"));
				books.setBook_name(rs.getString("book_name"));
				books.setBook_number(rs.getString("book_number"));
				books.setBook_sum(rs.getString("book_sum"));
				book.add(books);
			}
		}finally{
			JdbcTool.close(rs, ps, con);
		}
		return book;
	}
	public Books get(int id,int bookId) throws ClassNotFoundException, SQLException{
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		Books books=new Books();
		try {
			con=JdbcTool.craeConnection();
			ps=con.prepareStatement("select id,book_name,book_number,book_sum from book where book_id=?and id=?");
			ps.setInt(1, bookId);
			ps.setInt(2, id);
			rs=ps.executeQuery();
			if (rs.next()){
				books.setId(id);
				books.setBook_name(rs.getString("book_name"));
				books.setBook_number(rs.getString("book_number"));
				books.setBook_sum(rs.getString("book_sum"));
			}
		}finally{
			JdbcTool.close(rs, ps, con);
		}
		return books;
	}
	public int update(Books books,int bookId) throws SQLException, ClassNotFoundException{
		Connection con=null;
		PreparedStatement ps=null;
		ResultSet rs=null;
		try {
			con=JdbcTool.craeConnection();
			ps=con.prepareStatement("update book set book_name=?,book_number=?,book_sum=?where id=? and book_id=?");
			ps.setString(1, books.getBook_name());
			ps.setString(2, books.getBook_number());
			ps.setString(3, books.getBook_sum());
			ps.setInt(4, books.getId());
			ps.setInt(5, bookId);
			return ps.executeUpdate();
		}finally{
			JdbcTool.close(rs, ps, con);
		}
	}
}
